package com.cloud.sample.util;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

public class ZipUtils {

    /**
     * 解压到指定目录
     *
     * @param file
     * @param targetPath
     * @throws IOException
     */
    public static void unzip(File file, String targetPath) throws IOException {
        if (StringUtils.isEmpty(targetPath)) {
            return;
        }

        ZipFile zipFile = new ZipFile(file);
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zipEntry = entries.nextElement();
            File targetFile = new File(targetPath + File.separator + zipEntry.getName());

            // 是目录则创建
            if (zipEntry.isDirectory()) {
                targetFile.mkdirs();
                continue;
            }

            // 判断父目录没有就创建
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }

            // 复制文件，inputStream自动关闭
            try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
                FileUtils.copyInputStreamToFile(inputStream, targetFile);
            }
        }
    }

}
